var timer = document.getElementById('timer');
var ali = document.getElementsByTagName('li');
var imgArr = ['./img/0.JPG', './img/1.JPG', './img/2.JPG', './img/3.JPG', './img/4.JPG', './img/5.JPG', './img/6.JPG', './img/7.JPG', './img/8.JPG', './img/9.JPG'];
initTimer();
setInterval(showTimer, 1000);

function showTimer() {
  var imgArr = new Array();
  var time = new Date();
  var str = asTwo(time.getHours()) + asTwo(time.getMinutes()) + asTwo(time.getSeconds());
  for (var i = 0; i < str.length; i++) {
    if (timer.num.charAt(i) != str.charAt(i)) {
      var sort = parseInt(ali[i].getAttribute('sort'));
      if (sort % 2 == 0) {
        ali[i].getElementsByTagName('img')[1].src = "./img/" + str.charAt(i) + '.JPG';
        doMove(ali[i].getElementsByTagName('img')[0], 'top', 2.4, -120, 10, true);
        doMove(ali[i].getElementsByTagName('img')[1], 'top', 1.2, 0, 10);
      } else {
        ali[i].getElementsByTagName('img')[0].src = "./img/" + str.charAt(i) + '.JPG';
        doMove(ali[i].getElementsByTagName('img')[1], 'top', 2.4, -120, 10, true);
        doMove(ali[i].getElementsByTagName('img')[0], 'top', 1.2, 0, 10);
      }
      sort++;
      ali[i].setAttribute('sort', sort);
    }
  }
  timer.num = str;
}

function initTimer() {
  var time = new Date();
  var str = asTwo(time.getHours()) + asTwo(time.getMinutes()) + asTwo(time.getSeconds());
  for (var i = 0; i < ali.length; i++) {
    ali[i].getElementsByTagName('img')[0].src = imgArr[str.charAt(i)];
  }
  timer.num = str;
}

/*
  为不满2位数字添加填充位
  num 原数字
*/
function asTwo(num) {
  return num < 10 ? '0' + num : '' + num;
}

/*
  元素移动
  obj 要移动的对象
  direction 要移动的方向，如top，left等
  speed 移动速度
  limit 极限边界值
  freq 频率
  endFn 回调函数
*/
function doMove(obj, direction, speed, limit, freq, move) {
  'use strict';
  speed = parseInt(getStyle(obj, direction)) < limit ? speed : -speed;
  clearInterval(obj.moveTimer);
  obj.moveTimer = setInterval(function () {
    var target = parseInt(getStyle(obj, direction)) + speed;
    if ((target > limit && speed > 0) || (target < limit && speed < 0)) {
      target = limit;
    }
    obj.style[direction] = target + 'px';
    if (target === limit) {
      clearInterval(obj.moveTimer);
      if (move) obj.style[direction] = 120 + 'px';
    }
  }, freq);
}

function getStyle(obj, attr) {
  return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
